<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="name" label="用户姓名" required>
        <uni-easyinput placeholder="反馈用户的姓名" v-model="formData.name"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="contact" label="联系方式" required>
        <uni-easyinput placeholder="用户的手机号或邮箱地址" v-model="formData.contact"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="type" label="反馈类型">
        <uni-data-checkbox v-model="formData.type" :localdata="formOptions.type_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="description" label="详细描述" required>
        <uni-easyinput placeholder="反馈的详细描述内容" v-model="formData.description"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="images" label="图片附件">
        <uni-data-checkbox :multiple="true" v-model="formData.images"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="clientIP" label="客户端IP">
        <uni-easyinput placeholder="提交反馈时的客户端IP地址" v-model="formData.clientIP"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="userAgent" label="用户代理">
        <uni-easyinput placeholder="客户端的User-Agent信息" v-model="formData.userAgent"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="source" label="来源">
        <uni-easyinput placeholder="反馈来源（小程序、H5等）" v-model="formData.source"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="createTime" label="创建时间戳">
        <undefined v-model="formData.createTime"></undefined>
      </uni-forms-item>
      <uni-forms-item name="createDate" label="创建日期">
        <uni-datetime-picker return-type="date" v-model="formData.createDate"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="status" label="处理状态">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="priority" label="优先级">
        <uni-data-checkbox v-model="formData.priority" :localdata="formOptions.priority_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="adminReply" label="管理员回复">
        <uni-easyinput placeholder="管理员对反馈的回复内容" v-model="formData.adminReply"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="replyTime" label="回复时间">
        <uni-datetime-picker return-type="date" v-model="formData.replyTime"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="tags" label="标签">
        <uni-data-checkbox :multiple="true" v-model="formData.tags"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="isDeleted" label="是否删除">
        <switch @change="binddata('isDeleted', $event.detail.value)" :checked="formData.isDeleted"></switch>
      </uni-forms-item>
      <uni-forms-item name="version" label="版本号">
        <uni-easyinput placeholder="数据结构版本号" v-model="formData.version"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/feedback.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'feedback';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "name": "",
        "contact": "",
        "type": "",
        "description": "",
        "images": [],
        "clientIP": "",
        "userAgent": "",
        "source": "",
        "createTime": null,
        "createDate": null,
        "status": "",
        "priority": "",
        "adminReply": "",
        "replyTime": null,
        "tags": [],
        "isDeleted": null,
        "version": ""
      }
      return {
        formData,
        formOptions: {
          "type_localdata": [
            {
              "value": "功能建议",
              "text": "功能建议"
            },
            {
              "value": "问题反馈",
              "text": "问题反馈"
            },
            {
              "value": "使用体验",
              "text": "使用体验"
            },
            {
              "value": "其他",
              "text": "其他"
            }
          ],
          "status_localdata": [
            {
              "value": "pending",
              "text": "pending"
            },
            {
              "value": "processing",
              "text": "processing"
            },
            {
              "value": "resolved",
              "text": "resolved"
            },
            {
              "value": "closed",
              "text": "closed"
            }
          ],
          "priority_localdata": [
            {
              "value": "low",
              "text": "low"
            },
            {
              "value": "normal",
              "text": "normal"
            },
            {
              "value": "high",
              "text": "high"
            },
            {
              "value": "urgent",
              "text": "urgent"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("name,contact,type,description,images,clientIP,userAgent,source,createTime,createDate,status,priority,adminReply,replyTime,tags,isDeleted,version").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
